//
//  WriteCharactWithAckAction.swift
//  Clock
//
//  Created by 方强 on 16/7/4.
//  Copyright © 2016年 MT. All rights reserved.
//

import UIKit
import CoreBluetooth

public class WriteCharactWithAckAction: BLEBaseAction {
    private var sendCharact:CBCharacteristic?;
    private var reviceCharact:CBCharacteristic?;
    private var datas:Data?;
    
    public init(sendCharact:CBCharacteristic?, reviceCharact:CBCharacteristic?, datas:Data?, option:BLEBaseAction_ActionOption!){
        super.init(type: BLEBaseAction_ActionType.WRITECHACTWITHACK, option: option);
        
        self.sendCharact = sendCharact;
        self.reviceCharact = reviceCharact;
        self.datas = datas;
    }
    
    // 提取分段后的数据
    private var point:Int = 0;
    
    public func getPerdatas() -> Data?{
        if ((datas == nil) || (point >= datas!.count)) {
            return nil;
        }
        var getbyte:Data?;
        if ((option.getPerlenght() + point) > datas!.count) {
//            getbyte = datas?.subdataWithRange(NSRange(location: point, length: (datas?.length)! - point));
            getbyte = datas!.subdata(in: point ..< datas!.count);
        } else{
//            getbyte = datas?.subdataWithRange(NSRange(location: point, length: option.getPerlenght()));
            getbyte = datas!.subdata(in: point ..< (point+option.getPerlenght()));
        }
        if(getbyte != nil){
            point += getbyte!.count;
        }
        
        return getbyte;
    }
    
    public func getSendCharact() -> CBCharacteristic?{
        return sendCharact;
    }
    
    public func setSendCharact(sendCharact:CBCharacteristic?) {
        self.sendCharact = sendCharact;
    }
    
    public func getReviceCharact() -> CBCharacteristic?{
        return reviceCharact;
    }
    
    public func setReviceCharact(reviceCharact:CBCharacteristic?) {
        self.reviceCharact = reviceCharact;
    }
    
    public var onSendDatas:((Data)->Void)?;
    
    // 接收数据
    public var onReciveDatas:((WriteCharactWithAckAction, CBCharacteristic, Data?)->Void)?;
}
